package com.mljr.example.service;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mljr.example.R;
import com.mljr.example.bean.AppVersion;
import com.mljr.example.util.AppUtils;
import com.mljr.example.widget.dialog.CustomDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author andyhome
 * @date 2014-12-26
 */

public class UpdateManager {
	/* 下载中 */
	private static final int DOWNLOAD = 1;
	private static final int DOWNLOAD_FAILED = -1;
	/* 下载结束 */
	private static final int DOWNLOAD_FINISH = 2;
	/* 保存解析的XML信息 */
	// HashMap<String, String> mHashMap;
	/* 下载保存路径 */
	private String mSavePath;
	/* 记录进度条数量 */
	private int progress;
	/* 是否取消更新 */
	private boolean cancelUpdate = false;

	private Context mContext;

	private boolean showDowloadProgress = true;

	private AppVersion appVersion;
	/* 更新进度条 */
	private ProgressBar mProgress;
	private TextView updateProgressNumber;
	private Dialog mDownloadDialog;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 正在下载
			case DOWNLOAD:
				// 设置进度条位置
				mProgress.setProgress(progress);
				updateProgressNumber.setText(progress + "%");
				break;
			case DOWNLOAD_FINISH:
				// 安装文件
				installApk(appVersion.getApkName());
				break;
	        case DOWNLOAD_FAILED:
					Toast.makeText(mContext, "下载失败，请检查网络环境", Toast.LENGTH_LONG).show();
					showNoticeDialog();
					break;
			default:
				break;
			}
		};
	};

	public UpdateManager(Context context, AppVersion appVersion) {
		this.appVersion = appVersion;
		this.mContext = context;
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			// 获得存储卡的路径
			String sdpath = Environment.getExternalStorageDirectory() + "/";
			mSavePath = sdpath + "download";

		} else {
			String sdpath  = Environment.getDownloadCacheDirectory() +"/";
			mSavePath = sdpath + "download";
			//
		}



	}

	/**
	 * 检测软件更新
	 */
	public void checkUpdate(boolean showToast) {
		if (isUpdate()) {
			// 显示提示对话框
			showNoticeDialog();
		} else {
			if(showToast){
				Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
			}

		}
	}

	/**
	 * 检查软件是否有更新版本
	 * 
	 * @return
	 */
	private boolean isUpdate() {
		// 获取当前软件版本
		String versionName = getVersionName();

		// 版本判断
		if (compareVersion(appVersion.getVersion(), versionName) == 1) {
			return true;
		}
		return false;
	}
	
	public static boolean hasNewVersion(String appVersionNum) {
		if(appVersionNum==null){
			return false;
		}
		// 获取当前软件版本
		String versionName = getVersionName();

		// 版本判断
		if (compareVersion(appVersionNum, versionName) == 1) {
			return true;
		}
		return false;
	}

	
	private boolean isForceUpdate() {
		// 获取当前软件版本
		String versionName = getVersionName();
		
		// 版本判断
		if (compareVersion(appVersion.getUpgradeBelow(), versionName) == 1) {
			return true;
		}
		return false;
	}

	/**
	 * 获取软件版本号
	 * 
	 * @return
	 */
	public static String getVersionName() {
		String versionName = "";
		try {
			// 获取软件版本号，对应AndroidManifest.xml下android:versionCode
			versionName = AppUtils.getContext().getPackageManager().getPackageInfo(AppUtils.getContext().getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionName;
	}

	/**
	 * 显示软件更新对话框
	 */
	private void showNoticeDialog() {


		// 显示下载对话框
		final  File apkfile = new File(mSavePath, appVersion.getApkName());

		CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
		if(apkfile.exists()&&!checkApkVersion(mContext,appVersion,apkfile.getAbsolutePath())){
			apkfile.delete();//包名和实际版本不一致，（原因：1、下载更新时用可能下载到老的缓存中的，2、更新时忘记替换包了，用户下载到老版本 ）
		}

		if (!apkfile.exists()) {
			builder.setMessage("最新版本"+appVersion.getVersion()+"\n\n更新内容\n"+appVersion.getDescription());
		} else {
			builder.setMessage("最新版本"+appVersion.getVersion()+"\n"+"最新版本已经下载，是否安装？"+"\n\n更新内容\n"+appVersion.getDescription());
		}

		builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if(!isForceUpdate()){
					dialog.dismiss();
				}


				File file = new File(mSavePath);
				// 判断文件目录是否存在
				if (!file.exists()) {
					file.mkdir();

				}
				if(!file.canWrite()){
					Toast.makeText(mContext, "请检查相关权限，无法保存文件到存储卡", Toast.LENGTH_LONG).show();
					return ;
				}

				if (apkfile.exists()) {
					installApk(appVersion.getApkName());
				} else {
					showDownloadDialog();
				}

			}
		});

		if(isForceUpdate()){

			builder.setNegativeButton("退出应用", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					AppUtils.exitSys();
				}
			});
		}else {
			builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
		}


		builder.appUpdateNotice().show();

	}

	/**
	 * 显示软件下载对话框
	 */
	public void showDownloadDialog() {
		// 构造软件下载对话框
		Builder builder = new Builder(mContext);
		builder.setTitle(R.string.soft_updating);
		// 给下载对话框增加进度条
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.progress_softupdate, null);
		mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
		updateProgressNumber = (TextView) v.findViewById(R.id.update_progress_number);
		builder.setView(v);
		// 取消更新
		builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				// 设置取消状态
				cancelUpdate = true;
				if(isForceUpdate()){
					AppUtils.exitSys();
				}
			}
		});
		mDownloadDialog = builder.create();
		mDownloadDialog.setCancelable(false);
		mDownloadDialog.show();
		// 现在文件
		downloadApk();
	}

	/**
	 * 下载apk文件
	 */
	private void downloadApk() {
		// 启动新线程下载软件
		new downloadApkThread().start();
	}

	/**
	 * 下载文件线程
	 * 
	 * @author coolszy
	 * @date 2012-4-26
	 * @blog http://blog.92coding.com
	 */
	private class downloadApkThread extends Thread {
		@Override
		public void run() {
			try {
				// 判断SD卡是否存在，并且是否具有读写权限

					// 获得存储卡的路径

					URL url = new URL(appVersion.getUrl());
					// 创建连接
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.connect();
					// 获取文件大小
					int length = conn.getContentLength();
					// 创建输入流
					InputStream is = conn.getInputStream();

					File file = new File(mSavePath);
					// 判断文件目录是否存在
					if (!file.exists()) {
						file.mkdir();
					}
					File apkFile = new File(mSavePath, appVersion.getApkName());
					FileOutputStream fos = new FileOutputStream(apkFile);
					int count = 0;
					// 缓存
					byte buf[] = new byte[1024];
					// 写入到文件中
					do {
						int numread = is.read(buf);
						count += numread;
						// 计算进度条位置
						progress = (int) (((float) count / length) * 100);
						// 更新进度
						mHandler.sendEmptyMessage(DOWNLOAD);
						if (numread <= 0) {
							// 下载完成
							mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
							break;
						}
						// 写入文件
						fos.write(buf, 0, numread);
					} while (!cancelUpdate);// 点击取消就停止下载.
					fos.close();
					is.close();

			} catch (Exception e) {

				mHandler.sendEmptyMessage(DOWNLOAD_FAILED);

			}
			// 取消下载对话框显示
			mDownloadDialog.dismiss();
		}
	}

	/**
	 * 安装APK文件
	 */
	private void installApk(String apkName) {
		File apkfile = new File(mSavePath, apkName);

		if (!apkfile.exists()) {
			return;
		}else{
			if(!checkApkVersion(mContext,appVersion,apkfile.getAbsolutePath())){
				apkfile.delete();//包名和实际版本不一致，（原因：1、下载更新时用可能下载到老的缓存中的，2、更新时忘记替换包了，用户下载到老版本 ）
				return;
			}
		}
		// 通过Intent安装APK文件

		Intent install = new Intent();
		install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		install.setAction(Intent.ACTION_VIEW);
		install.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		mContext.startActivity(install);
	}


	public static boolean  checkApkVersion(Context context,AppVersion appVersion, String filePath){
		PackageManager packageManager = context.getPackageManager();
		PackageInfo packageInfo = packageManager.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES);
		if(packageInfo!=null&&compareVersion(packageInfo.versionName, appVersion.getVersion())>=0){
			return true;
		}else{
			return false;
		}

	}

	//比较版本号

	public static int compareVersion(String version1, String version2) {
		if (version1 == null || version1.length() == 0 || version2 == null || version2.length() == 0) {
			return 0;
		}
		String[] versionArray1 = version1.split("\\.");//注意此处为正则匹配，不能用.；
		String[] versionArray2 = version2.split("\\.");
		int idx = 0;
		int minLength = Math.min(versionArray1.length, versionArray2.length);//取最小长度值
		int diff = 0;
		while (idx < minLength){
			diff = compareNumber(Integer.parseInt(versionArray1[idx]),Integer.parseInt(versionArray2[idx]));
			if(diff==0){
				++idx;
			}else{
				break;
			}

		}
		//如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大；
		diff = (diff != 0) ? diff : compareNumber(versionArray1.length,versionArray2.length);
		return diff;
	}
	//比较数字
	private static int compareNumber(int v1,int v2){
		int diff = 0;
		if(v1>v2){
			diff = 1;
		}else if(v1==v2){
			diff = 0 ;
		}else{
			diff = -1;
		}
		return diff;
	}

}
